// ignore_for_file: non_constant_identifier_names
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sj001/model/ChatMsgItem.dart';
import 'package:sj001/model/conversatinoMessageModel.dart';
import 'package:sj001/model/revMsgModel.dart';
import 'package:sj001/pages/chatPage/chatItem.dart';
import 'package:sj001/pages/views/inputTextfield.dart';
import 'package:sj001/request/request.dart';
import '../../model/inputMessage.dart';

class ChatPage extends StatefulWidget {
  ChatPage({required this.conversation_id, this.showAppBar = false, Key? key})
      : super(key: key);
  String conversation_id;
  bool showAppBar;

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  RxList<Rx<ChatMsgItem>> list = <Rx<ChatMsgItem>>[].obs;
  ScrollController ctr = ScrollController();
  final RefreshController refreshController =
      RefreshController(initialRefresh: false);
  RxBool isRequesting = false.obs;
  RxBool canCancel = false.obs;
  String? current_task_id;

  @override
  initState() {
    super.initState();

    if (widget.conversation_id.isNotEmpty) {
      requestHistory('');
    }
  }

  requestHistory(String first_id) async {
    ConversationMessageModel? model = await CustomRequest.conversationsMessages(
        conversation_id: widget.conversation_id, first_id: first_id);
    refreshController.refreshCompleted();
    if (model != null) {
      list.insertAll(0, model.trans2ChatMsgItem());
      list.refresh();
      scrollToEnd();
    }
  }

  requestNext(String message_id) async {
    await CustomRequest.nextSuggest(message_id: message_id);
  }

  onSend(InputMessageModel model) {
    if (isRequesting.value) return;
    isRequesting.value = true;
    CustomRequest.sendMessageStreaming(
      conversation_id: widget.conversation_id,
      model: model,
      onData: onData,
      onDone: onDone,
      onError: onError,
      onDataError: onDataError,
    );

    //  添加用户发送的
    list.add(
      ChatMsgItem(
        user: 1,
        message_id: DateTime.now().millisecond.toString().obs,
        models: [RevMsgModel(answer: model.content)].obs,
        isDone: true.obs,
        conversation_id: widget.conversation_id,
        isLike: false.obs,
        createAt: (DateTime.now().millisecondsSinceEpoch~/1000).obs,
      ).obs,
    );

    // 天加一个等待消息
    list.add(
      ChatMsgItem(
        user: 2,
        createAt: (DateTime.now().millisecondsSinceEpoch~/1000).obs,
        message_id: DateTime.now().millisecond.toString().obs,
        models: [RevMsgModel(answer: '')].obs,
        isDone: false.obs,
        conversation_id: widget.conversation_id,
        isLike: false.obs,
      ).obs,
    );

    list.refresh();
    scrollToEnd();
  }

  onData(RevMsgModel rsp) {
    current_task_id = rsp.task_id;
    handleData(rsp, false);
    canCancel.value = true;
  }

  onError(String error) {
    list.removeWhere((element) => element.value.user == 2);
    list.refresh();
    isRequesting.value = false;
    canCancel.value = false;
  }

  onDataError(RevMsgModel rsp) {
    rsp.answer = rsp.message??'';
    handleData(rsp, true);
    isRequesting.value = false;
    canCancel.value = false;
  }

  onDone(RevMsgModel rsp) {
    handleData(rsp, true);
    // requestNext(rsp.message_id??'');
    isRequesting.value = false;
    canCancel.value = false;
  }

  handleData(RevMsgModel rsp, bool isDone) {
    Rx<ChatMsgItem>? item = list
        .where((p0) => p0.value.message_id == rsp.message_id)
        .toList()
        .firstOrNull;
    list.removeWhere((element) => element.value.user == 2);
    if (item == null) {
      item = ChatMsgItem(
        createAt: (rsp.created_at ?? 0).obs,
        message_id: (rsp.message_id ?? '').obs,
        models: [rsp].obs,
        isDone: isDone.obs,
        user: 0,
        conversation_id: rsp.conversation_id ?? '',
        isLike: false.obs,
      ).obs;
      list.value.add(item);
    } else {
      item.value.isDone.value = isDone;
      item.value.models.add(rsp);
    }
    widget.conversation_id = rsp.conversation_id ?? '';
    list.refresh();
    scrollToEnd();
  }

  scrollToEnd() {
    Future.delayed(const Duration(milliseconds: 10), () {
      ctr.animateTo(
        ctr.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    });
  }

  onNew() {
    list.clear();
    list.refresh();
    widget.conversation_id = '';
  }

  onLike(Rx<ChatMsgItem> item) async{
    bool ret = await CustomRequest.messageLike(message_id: item.value.message_id.value,rating: 'like');
    if (ret){
      item.value.isLike.value = true;
      list.refresh();
    }
  }

  onCancel(){
    if (canCancel.value && current_task_id != null){
      CustomRequest.cancelTask(task_id: current_task_id??'');
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: widget.showAppBar ? AppBar() : null,
      body: Container(
        decoration: const BoxDecoration(
          color: Color(0x80eeeeee),
        ),
        child: Column(
          children: [
            getList(),
            getStopButton(),
            InputTextfield(
              onSend: onSend,
              onNew: onNew,
              isRequesting: isRequesting,
            ),
          ],
        ),
      ),
    );
  }

  Widget getStopButton() {
    return Obx(
      () => Visibility(
        visible: canCancel.value,
        child: InkWell(
          onTap: onCancel,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(25),
              border: Border.all(
                color: Colors.black,
                width: 0.5,
              ),
            ),
            child: Text('停止生成'),
          ),
        ),
      ),
    );
  }

  Widget getList() {
    Widget child = Obx(() => ListView.builder(
          controller: ctr,
          itemBuilder: (ctx, index) {
            return Obx(() => ChatItem(
                  list[index],
                  onLike: onLike,
                ));
          },
          itemCount: list.length,
        ));
    return Expanded(
      child: SmartRefresher(
        enablePullDown: true,
        enablePullUp: false,
        header: const WaterDropHeader(),
        controller: refreshController,
        onRefresh: () {
          requestHistory(list.firstOrNull?.value.message_id.value ?? '');
        },
        child: child,
      ),
    );
  }
}
